package com.matou.auth.translator;

import com.matou.commons.constants.Resp;
import com.matou.commons.exception.MtError;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.common.exceptions.UnsupportedGrantTypeException;
import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator;
import org.springframework.stereotype.Component;
import org.springframework.web.HttpRequestMethodNotSupportedException;

/**
 * @Author CM
 * @Date 2021/5/9 9:22
 * @Description CmWebResponseExceptionTranslator 异常翻译器
 * @Version 1.0
 */
@Slf4j
@Component
public class CmWebResponseExceptionTranslator implements WebResponseExceptionTranslator {

    protected final String INVALID_REFRESH_TOKEN="Invalid refresh token";
    protected final String LOCKED="locked";

    @Override
    public ResponseEntity translate(Exception e) throws Exception {
        ResponseEntity.BodyBuilder status = ResponseEntity.status(HttpStatus.OK);
        log.warn("认证失败",e);
        if (e instanceof UnsupportedGrantTypeException) {
            // "不支持该认证类型";
            return status.body(Resp.failure(MtError.MT_000002));
        }
        if(e instanceof HttpRequestMethodNotSupportedException){
            // "请求类型错误,请切换POST请求";
            return status.body(Resp.failure(MtError.MT_000003));
        }
        if (e instanceof InvalidGrantException) {
            if (StringUtils.containsIgnoreCase(e.getMessage(), INVALID_REFRESH_TOKEN)) {
                // "refresh token无效";
                return status.body(Resp.failure(MtError.MT_000004));
            }
            if (StringUtils.containsIgnoreCase(e.getMessage(), LOCKED)) {
                //  "用户已被锁定，请联系管理员";
                return status.body(Resp.failure(MtError.MT_000005));
            }
            // "用户名或密码错误";
            return status.body(Resp.failure(MtError.MT_000006));
        }
        // "认证失败";
        return status.body(Resp.failure(MtError.MT_000007));
    }
}
